package apigateway.project.core.response;

import apigateway.project.commen.enums.ResponseCode;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponseStatus;
import lombok.Data;
import org.asynchttpclient.Response;

import java.util.HashMap;

@Data
public class GlobalResponse {
    /**
     * 响应头
     */
    private HttpHeaders headers =  new DefaultHttpHeaders();
    /**
     * 响应内容
     */
    private String content;
    /**
     *  响应码
     */
    private HttpResponseStatus status;
    /**
     * (核心)返回对象
     */
    private Response response;

    public static GlobalResponse buildGlobalResponse(Response res){
        GlobalResponse response = new GlobalResponse();
        response.setResponse(res);
        response.setStatus(HttpResponseStatus.valueOf(res.getStatusCode()));
        return response;
    }
    public static GlobalResponse buildGlobalResponse(String msg){
        GlobalResponse response = new GlobalResponse();
        response.setContent(msg);
        return response;
    }

    public static GlobalResponse buildGlobalResponse(ResponseCode code) {
        HashMap<String, String> map = new HashMap<>();
        GlobalResponse response = new GlobalResponse();

        map.put("status", String.valueOf(code.getStatus().code()));
        map.put("code", String.valueOf(code.getCode()));
        map.put("msg",code.getMsg());

        ObjectMapper mapper = new ObjectMapper();
        String json = null;
        try {
            json = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        response.setStatus(code.getStatus());
        response.setContent(json);

        return response;
    }
}
